package io.zhengsh.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class ServerSocketChannelDemo {

	public static void main(String[] args) throws IOException, InterruptedException {
		int port = 8888;
		ByteBuffer buffer = ByteBuffer.wrap("hell0 world!".getBytes(StandardCharsets.UTF_8));

		ServerSocketChannel socketChannel = ServerSocketChannel.open();
		socketChannel.socket().bind(new InetSocketAddress(port));

		socketChannel.configureBlocking(false);

		while (true) {
			System.out.println("Waiting for connections");
			SocketChannel sc = socketChannel.accept();
			if (sc == null) {
				System.out.println("null");
				TimeUnit.SECONDS.sleep(2);
			} else {
				System.out.println("Incoming conection form: " +
						sc.socket().getRemoteSocketAddress());
				buffer.rewind();
				sc.write(buffer);
				sc.close();
			}
		}

	}
}
